﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;

namespace ASTClass
{
    class IfAST : AST
    {
        public IfAST() : base() { name = "If"; }
        public IfAST(AST parent) : base(parent) { name = "If"; }

        public override AST Clone()
        {
            IfAST ast = new IfAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());

            return ast;
        }

        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern

        public override void CodeGen(Taste.SymbolTable symTab, Taste.CodeFileGen cfg)
        {
            if (ChildCount() > 0)
            {
                children[0].CodeGen(symTab, cfg);
                cfg.AddCommand("lw", "$t0, 0($sp)");
                cfg.AddCommand("addiu", "$sp, $sp, 4");
                cfg.AddCommand("beqz", "$t0, _" + this.UniqueName + "else");
                if (ChildCount() > 1)
                {
                    children[1].CodeGen(symTab, cfg);
                    cfg.AddCommand("j", "_" + this.UniqueName + "end");
                }
                cfg.AddFuncName("_" + this.UniqueName + "else");
                if (ChildCount() > 2)
                {
                    children[2].CodeGen(symTab, cfg);
                }
                cfg.AddFuncName("_" + this.UniqueName + "end");
            }
        }
    }
}
